'use strict';

/* Controllers */
// signin controller
app.controller('SigninFormController', ['$rootScope', '$scope', '$state', '$window', 'userService', 'authenticationService', function ($rootScope, $scope, $state, $window, userService, authenticationService) {
    $scope.user = {};
    $scope.authError = null;

    userService.logout($window.sessionStorage.token).then(function (response) {
        if (response.data) {
            $window.sessionStorage.token = "";
        }
    }, function (response) {
        $window.sessionStorage.token = "";
    });

    $scope.login = function () {
        $scope.authError = null;
        // Try to login
        userService.login($scope.user.email, $scope.user.password)
            .then(function (response) {
                // console.info("SigninFormController.login: ", response);
                if (!response.data.Response) {
                    $scope.authError = 'Email or Password not right';
                } else {
                    if (response.data.Error != null) {
                        $scope.authError = response.data.Error.Message.split('\n')[0];
                        return;
                    }
                    authenticationService.isLogged = true;
                    $window.sessionStorage.token = response.data.Response.Info.Token;
                    $window.sessionStorage.userInfo = response.data.Response.Info;
                    $rootScope.$broadcast('SigninFormController:SignedIn', response.data.Response.Info);
                    $state.go('app.management.user');
                }
            }, function (x) {
                $scope.authError = 'Server Error';
            });
    };
}]);